const router = require('koa-router')()
const Dept = require('../modules/DeptSchema')
const util = require('../utils/util.js')

router.prefix('/dept')

router.get('/list', async (ctx) => {
  const { deptName } = ctx.request.query
  let params = {}
  if (deptName) {
    params.deptName = deptName
  }
  try {
    const list = await Dept.find(params)
    if (deptName) {
      ctx.body = util.success(list, '查询成功')
    } else {
      const data = getTreeDept(list, null, [])
      ctx.body = util.success(data, '查询成功')
    }
  } catch (error) {
    ctx.body = util.fail(`异常错误:${error.stack}`)
  }
})

/**
 * 树型菜单处理
 * @param {Array} data 数据库扁平数据
 * @param {String} id 键值ID
 * @param {Array} list 引用类型
 * @returns
 */
function getTreeDept(data, id, list) {
  for (let i = 0; i < data.length; i++) {
    let item = data[i]
    if (String(item.parentId.slice().pop()) == String(id)) {
      list.push(item._doc)
    }
  }
  list.map((item) => {
    item.children = []
    getTreeDept(data, item._id, item.children)
    // 判断按钮
    if (item.children.length == 0) {
      delete item.children
    }
  })
  return list
}

router.post('/operate', async (ctx) => {
  const { _id, action, ...params } = ctx.request.body
  let res, info
  try {
    if (action == 'add') {
      info = '创建成功'
      res = await Dept.create(params)
    } else if (action == 'edit') {
      info = '编辑成功'
      params.updateTime = new Date()
      res = await Dept.findByIdAndUpdate(_id, params)
    } else if (action == 'delete') {
      info = '删除成功'
      await Dept.findByIdAndRemove(_id)
      await Dept.deleteMany({ parentId: { $all: [_id] } })
    }
    ctx.body = util.success(res, info)
  } catch (error) {
    ctx.body = util.fail(`异常错误:${error.stack}`)
  }
})

module.exports = router
